package ruc.DolphinDB.write;

import com.xxdb.DBConnection;
import ruc.Consts.constant;
import ruc.DolphinDB.DolphinDB_Common;
import ruc.utils.IOUtils;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;


public class DolphinDB_MultiTableWrite {
    private int port;
    private String IP,tbName;

    public DolphinDB_MultiTableWrite(String IP, int port, String tbName) {
        this.IP = IP;
        this.port = port;
        this.tbName = tbName;
    }

    private void insert(String[] values, int[] tableNum) throws IOException, InterruptedException {
        int idx = 0;
        String format = "insert into %s values(%s,'%s','%s','%s',%s, %s, %s)";
        DBConnection conn = DolphinDB_Common.getDBConnection(IP, port);
        int[] cnt = new int[tableNum.length];
        while(idx < values.length) {
            for(int i = 0; i < tableNum.length; i++) {
                long st_Time = System.nanoTime();
                CountDownLatch countDownLatch = new CountDownLatch(tableNum[i]);
                boolean status = false;
                for(int j = 0; j < tableNum[i]; j++) {
                    if (idx == values.length) {
                        System.out.printf("[TSBench-D] >>>>>>>> index out of bounds, the length of array:%d >>>>>>>>>>>> \n", values.length);
                        status = true;
                        break;
                    }

                    String[] v = values[idx++].split(constant.Delimiter);
                    String sql = String.format(format, tbName + j, v[0], v[1], v[2], v[3], v[4], v[5], v[6]);
                    //asynchronous insert
                    new Thread(()->{
                        try {
                            conn.run(sql);
                            countDownLatch.countDown();//countdown
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }).start();
                }

                if(status) {
                    break; // stop countdown
                }
                countDownLatch.await();
                cnt[i] += (System.nanoTime() - st_Time) / constant.Ns2Ms;
            }
        }

        for(int i = 0; i < cnt.length; i++) {
            System.out.printf("[TSBench-D] [DolphinDB_MultiTableWrite]>>>>>>>> TableNum %d, insert time %d 行 / ms >>>>>>>>>>>> \n", tableNum[i], cnt[i]);
            IOUtils.WriteData(constant.GetWriteFilePath("DolphinDB", "MultiTableWrite"),
                    new String[]{String.valueOf(tableNum[i]), String.valueOf(cnt[i])});
        }

        conn.close();
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        DolphinDB_MultiTableWrite db = new DolphinDB_MultiTableWrite(constant.IP, constant.DolphinDB_Port, constant.MultiTableWrite_tbName);
        db.insert(IOUtils.GetData(), constant.MutiTable_TableNum);
    }
}
